<template>
    <div style="height:100%;">
      <div>
        <div class='content-title'>
          <div class='content-title-parent'>系统管理</div>
          /
          <div class='content-title-child'>角色管理</div>
        </div>
        <hr class='content-hr'/>
      </div>
      <!--表格筛选条件-->
      <el-row class='categoryClass' style="margin-top:10px">
        <el-button type="warning" style="float:right;margin-right:20px" @click="addVisable = true">添加</el-button>
      </el-row>
      <!--表格数据-->
      <el-row style="margin-top:10px">
        <el-table
          v-loading="loading"
          :element-loading-text="loadingText"
          element-loading-spinner="el-icon-loading"
          :data="filterFormFro.tableData" 
          :border="true" 
          :row-class-name="tableRowClassName"
          :header-cell-class-name = "tableHeaderClassName"
          v-bind:style="{width: tableWidth + 'px'}">
            <el-table-column prop="index" label="序号" width="80">
            </el-table-column>
            <el-table-column prop="level" label="级别" width="100">
            </el-table-column>
            <el-table-column prop="roleName" label="角色名" sortable width="180">
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间" width="200">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  @click="handleAuthorize(scope.$index, scope.row)">角色授权</el-button>
                <el-button
                  size="mini"
                  type="success"
                  @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)">删除角色</el-button>
              </template>
            </el-table-column>
        </el-table>
      </el-row>
      <!-- 表格下方分页 -->
      <el-row>
        <div class="pagination" style="text-align:center" v-show="paginationVisible">
            <el-pagination
              @current-change="handleCurrentChange"
              background
              :current-page="filterForm.currentPage"
              :page-size="15"
              layout="total,prev, pager, next"
              :page-count="filterFormFro.totalPage">
            </el-pagination>
        </div>
      </el-row>
      <!-- 添加角色信息弹窗 -->
      <el-dialog title="增加角色:"   :visible.sync="addVisable"
          :closeOnClickModal="false" 
          width="550px"
          class="categoryManaDialog"
          :close-on-click-modal="false" 
          :close-on-press-escape="false"
          @close="resetForm('addForm')">
        <el-form :model='addForm' ref="addForm" :rules="addrules" label-width="170px">
            <el-form-item label="角色：" prop='roleName'>
              
              <!--
                //	<input onkeyup="value=value.replace(/[\W]/g,'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))">
              -->
              <!-- <input onkeyup="value=value.replace(/[\W]/g,'') " v-model="addForm.roleName"> -->
              <el-input  @keyup.native="enterEvent($event, 'addForm')" style='width:240px' v-model.trim="addForm.roleName" type="text" ></el-input>
              </el-form-item>
            <el-form-item label="级别：" prop="level">
              <el-select v-model="addForm.level" style="width:240px" clearable placeholder="请选择">
                  <el-option
                      v-for="item in levelList"
                      :key="item"
                      :value="item">
                  </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-button type="primary" style="width:240px" @click="submitForm('addForm')">提 交</el-button>
            </el-form-item>
        </el-form>
      </el-dialog>
      <!-- 编辑角色信息弹窗 -->
      <el-dialog title="编辑角色信息:"   :visible.sync="editVisable"
          :closeOnClickModal="false" 
          width="550px"
          class="categoryManaDialog"
          :close-on-click-modal="false" 
          :close-on-press-escape="false"
          @close="resetForm('editForm')">
        <el-form :model='editForm' :rules="editrules" ref="editForm" label-width="170px">
            <el-form-item label="角色"  prop="roleName">
              <!-- <el-input style='width:240px' v-model="editForm.roleName" type="text" ></el-input> -->
              <el-input  @keyup.native="enterEvent($event, 'editForm')" style='width:240px' v-model.trim="editForm.roleName" type="text" ></el-input>
            </el-form-item>
            <el-form-item label="级别："  prop="level">
              <el-select v-model="editForm.level" style="width:240px" clearable placeholder="请选择">
                  <el-option
                      v-for="item in levelList"
                      :key="item"
                      :value="item">
                  </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-button type="primary" style="width:240px" @click="submitForm('editForm')">提 交</el-button>
            </el-form-item>
        </el-form>
      </el-dialog>
      <!-- 角色授权信息弹窗 -->
      <el-dialog title="角色授权:"   :visible.sync="authorizeVisable"
          :closeOnClickModal="false" 
          width="450px"
          class="categoryManaDialog"
          :close-on-click-modal="false" 
          :close-on-press-escape="false">
          <el-form :model='authorizeForm'  ref="authorizeForm" label-width="130px">
            <el-form-item label="角色权限：">
              <label style="color:red">{{authorizeForm.roleName}}</label>
            </el-form-item>
          </el-form>
          <!-- <label style="width:170px">角色权限：</label>
          <label style="color:red">{{authorizeForm.roleName}}</label> -->
          <div class="inner" style="height:300px">
            <div class="innerbox">
              <el-form :model='authorizeForm'  ref="authorizeForm" label-width="130px">
                <el-form-item label="">
                  <el-tree
                    style="margin-top:10px"
                    :data="originData"
                    show-checkbox
                    ref="tree"
                    :default-expanded-keys="authorizeForm.defaultExpandedKeys"
                    :default-checked-keys="authorizeForm.defaultCheckedKeys"
                    node-key="id"
                    :props="defaultProps">
                  </el-tree>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <el-form label-width="100px">
            <el-form-item label="">
              <el-button type="primary" style="margin-top:10px" @click="submitCheckedNodes()">保存权限</el-button>
            </el-form-item>
          </el-form>
        <!-- <div slot="footer" class="dialog-footer">
          <el-button @click="setCancle" >取 消</el-button>
          <el-button type="primary" @click="submitCheckedNodes()" >保存权限</el-button>
        </div> -->
      </el-dialog>
    </div>
</template>
<style>
 .el-table .headerClass {
    background: #f0f9eb;
    text-align: center
  }
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
</style>
<script>
import '../../../static/css/businessPlat/common.css'
import '../../../static/css/businessPlat/categoryMana.css'
import apiBus from '../../api/businessPlat/apiBus.js'
const sideData = require('../../json/origin-sidebar.json')
export default {
  created () {
    this.getRoleListFro()
  },
  data () {
    var checkString = (rule, value, callback) => {
      value = value.replace(/[^\w\u4e00-\u9fa5\s]/g, '')
      callback()
    }
    return {
      itemNode: [],
      originData: sideData.businessPlat.items,
      defaultProps: {
        children: 'subs',
        label: 'title'
      },
      tableWidth: '',
      sideItems: sideData, // 侧边栏数据
      testData: [],
      testData2: [],
      paginationVisible: false, // 表格下方的分页是否显示
      pointVisible: false, // 后台请求数据提示是否显示
      Note: '', // 后台请求数据提示
      loading: false, // 表格数据加载框
      loadingText: '正在拼命加载中，请稍等......',
      authorizeVisable: false, // 角色授权弹窗
      formLabelWidth: '30%',
      authorizeForm: { // 角色授权表单
        roleName: '',
        roleId: '',
        defaultExpandedKeys: [], // 树形默认展开id数组
        defaultCheckedKeys: [], // 树形默认选择id数组
        lastData: [] // 发送给后台的修改后的角色侧边栏ID
      },
      addForm: {
        roleName: '', // 角色
        level: '' // 级别
      },
      originchildParentList: [[1, 8, 9, 10, 11], [2, 12, 13, 14], [5, 15, 16], [6, 17, 18], [7, 19, 20]],
      levelList: [1, 2, 3, 4, 5, 6, 7, 8, 9], // 角色级别列表
      addVisable: false,
      filterForm: {
        currentPage: 1 // 当前页数
      },
      filterFormFro: {
        tableData: [],
        totalPage: 0 // 总共页数
      },
      editVisable: false,
      editForm: {
        index: 0, // 行数
        roleName: '', // 角色
        level: '', // 级别
        submitTime: '' // 更新时间
      },
      deleteForm: {
        roleName: '' // 角色名称
      },
      editrules: {
        roleName: [
          { validator: checkString, trigger: 'blur' },
          { required: true, message: '请填写角色名', trigger: 'blur' },
          { max: 8, message: '角色名最多8个字符', trigger: 'blur' }
        ],
        level: [
          { required: true, message: '请选择级别', trigger: 'change' }
        ]
      },
      addrules: {
        roleName: [
          /* {
            validator (r, v, b) {
              v = v.replace(/[^\w\u4e00-\u9fa5\s]/g, '')
              console.log('validator')
              console.log(v)
              b()
            }
          }, */
          { validator: checkString, trigger: 'blur' },
          { required: true, message: '请填写角色名', trigger: 'blur' },
          { max: 8, message: '角色名最多8个字符', trigger: 'blur' }
        ],
        level: [
          { required: true, message: '请选择级别', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    enterEvent (ev, form) {
      console.log('enterEvent')
      this[form].roleName = this[form].roleName.replace(/[^\w\u4e00-\u9fa5\s]/g, '')
      console.log(this[form].roleName)
    },
    onkeyupEvent () {
      console.log('onkeyupEvent')
      this.addForm.roleName = this.addForm.roleName.replace(/[^\w\u4e00-\u9fa5\s]/g, '')
    },
    setCancle () {
      this.$nextTick(function () {
        this.$refs['authorizeForm'].resetFields()
      })
      this.authorizeVisable = false
    },
    // 点击角色授权弹窗中的保存权限
    submitCheckedNodes () {
      this.authorizeForm.lastData = this.selectTreeNode()
      for (let i = 0; i < this.authorizeForm.lastData.length; i++) {
        this.authorizeForm.lastData[i] = parseInt(this.authorizeForm.lastData[i] + 1)
      }
      this.authorizeRoleListFro()
    },
    // 判断该数组中是否存在某元素
    isHave (arr, num) {
      for (let i = 0; i < arr.length; i++) {
        if (num === arr[i]) {
          return i
        }
      }
      return -1
    },
    // 展示树形默认选项
    setDefaultTree () {
      let test = [[0, 7, 8], [4], [3, 12, 13]] // 测试数据
      for (let i = 0; i < test.length; i++) {
        this.authorizeForm.defaultExpandedKeys.push(test[i][0])
        if (test[i].length === 1) {
          this.authorizeForm.defaultCheckedKeys.push(test[i][0])
        } else if (test[i].length > 1) {
          for (let m = 1; m < test[i].length; m++) {
            this.authorizeForm.defaultCheckedKeys.push(test[i][m])
          }
        }
      }
    },
    // 树形权限选择得到最终对象及id数组
    selectTreeNode () {
      let childList = this.$refs.tree.getCheckedKeys(false)
      for (let i = 0; i < childList.length; i++) {
        for (let m = 0; m < this.originchildParentList.length; m++) {
          if (this.isInArray(this.originchildParentList[m], childList[i])) {
            if (!this.isInArray(childList, this.originchildParentList[m][0])) {
              childList.push(this.originchildParentList[m][0])
            }
            break
          }
        }
      }
      return childList
    },
    // 数组中是否有该元素
    isInArray (arr, value) {
      for (var i = 0; i < arr.length; i++) {
        if (value === arr[i]) {
          return true
        }
      }
      return false
    },
    // 将时间转化为字符串
    formatDateFro (now) {
      var year = now.getFullYear()
      var month = now.getMonth() + 1
      month = month < 10 ? '0' + month : month
      var date = now.getDate()
      date = date < 10 ? ('0' + date) : date
      var hour = now.getHours()
      hour = hour < 10 ? ('0' + hour) : hour
      var minute = now.getMinutes()
      minute = minute < 10 ? ('0' + minute) : minute
      var second = now.getSeconds()
      second = second < 10 ? ('0' + second) : second
      return year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second
    },
    // 退出验证
    resetForm (formName) {
      if (formName === 'addForm') {
        this.addVisable = false
      } else if (formName === 'editForm') {
        this.editVisable = false
      }
      this.$refs[formName].resetFields()
    },
    // 账户信息表单验证
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (formName === 'addForm') {
            // this.addVisable = false
            this.addRoleListFro()
          } else if (formName === 'editForm') {
            // this.editVisable = false
            this.editRoleListFro()
          }
        } else {
          return false
        }
      })
    },
    // 分页页面跳转时
    handleCurrentChange (val) {
      this.filterForm.currentPage = val
      this.getRoleListFro()
    },
    tableHeaderClassName ({row, column, rowIndex, columnIndex}) {
      if (rowIndex === 0) {
        return 'headerClass'
      }
    },
    tableRowClassName ({row, rowIndex}) {
      return 'rowClass'
    },
    // 表格中点击角色授权，弹窗授权树形框
    handleAuthorize (index, row) {
      let data = this.filterFormFro.tableData[index]
      this.authorizeForm.roleName = data.roleName
      this.authorizeForm.roleId = data.roleId
      this.authorizeForm.adminId = data.adminId
      this.authorizeForm.defaultExpandedKeys = []
      this.authorizeForm.defaultCheckedKeys = []
      this.getSideItemsFro()
      // this.setDefaultTree()
    },
    // 表格中点击编辑按钮弹出点击弹窗口，补充数据
    handleEdit (index, row) {
      let data = this.filterFormFro.tableData[index]
      this.editVisable = true
      this.editForm.roleName = data.roleName
      this.editForm.level = data.level
      this.editForm.roleId = data.roleId
    },
    // 表格中点击删除
    handleDelete (index, row) {
      let data = this.filterFormFro.tableData[index]
      this.deleteForm.roleId = data.roleId
      this.$confirm('确定要删除该角色吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteRoleListFro()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    cancleEdit (formName) {
      this.resetError(formName)
      this.editVisable = false
    },
    // 重置表单
    resetError (formName) {
      this.$nextTick(function () {
        this.$refs[formName].resetFields()
      })
    },
    getChildIdList (testData) {
      let roleIdListTest = []
      for (let i = 0; i < testData.length; i++) {
        if (testData[i].menus.length > 0) {
          for (let m = 0; m < testData[i].menus.length; m++) {
            roleIdListTest.push(parseInt(testData[i].menus[m].permissionId) - 1)
          }
        } else {
          roleIdListTest.push(parseInt(testData[i].permissionId) - 1)
        }
      }
      let flag = 0
      roleIdListTest.filter(item => {
        if (item === 0) {
          flag = 1
        }
      })
      if (!flag) {
        roleIdListTest.push(0)
      }
      return roleIdListTest
    },
    getParentIdList (testData) {
      let roleIdListTest = []
      for (let i = 0; i < testData.length; i++) {
        roleIdListTest.push(parseInt(testData[i].permissionId) - 1)
      }
      return roleIdListTest
    },
    // 处理获得账户roleIdlist
    getRoleIdList (testData) {
      let roleIdListTest = []
      for (let i = 0; i < testData.length; i++) {
        roleIdListTest.push(parseInt(testData[i].permissionId) - 1)
        if (testData[i].menus.length > 0) {
          for (let m = 0; m < testData[i].menus.length; m++) {
            roleIdListTest.push(parseInt(testData[i].menus[m].permissionId) - 1)
          }
        }
      }
      return roleIdListTest
    },
    /** 提交后台相关函数 */
    // 向后台查看角色列表
    getRoleListFro () {
      this.loading = true
      this.paginationVisible = false
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token')
        }),
        body: JSON.stringify({
          pageNum: parseInt(this.filterForm.currentPage) // 当前页面数
        })
      }
      apiBus.getRoleList(para).then(res => {
        this.loading = false
        if (res.data.body.result === 1000) {
          this.filterFormFro.tableData = []
          let resData = res.data.body.content.list
          if (resData.length > 0) {
            this.filterFormFro.tableData = resData
            this.filterFormFro.pageNum = res.data.body.content.pageNum
            for (let i = 0; i < resData.length; i++) {
              this.filterFormFro.tableData[i].index = (parseInt(this.filterForm.currentPage) - 1) * 15 + i + 1
              this.filterFormFro.tableData[i].updateTime = this.formatDateFro(new Date(this.filterFormFro.tableData[i].updateTime))
            }
            this.filterFormFro.totalPage = res.data.body.content.allPage
            this.filterFormFro.totalPage > 1 ? this.paginationVisible = true : this.paginationVisible = false
          } else {
            this.$message.warning('没有相关角色信息！')
          }
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.loading = false
        this.$message.error(error)
      })
    },
    // 向后台增加角色信息
    addRoleListFro () {
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token')
        }),
        body: JSON.stringify({
          roleName: this.addForm.roleName,
          level: parseInt(this.addForm.level)
        })
      }
      console.log(para)
      apiBus.addRoleList(para).then(res => {
        if (res.data.body.result === 1000) {
          this.$message.success('添加角色成功！')
          this.addVisable = false
          this.filterForm.currentPage = 1
          this.getRoleListFro()
        } else if (res.data.body.result === 4001) {
          this.$message.error(res.data.body.resultDesp)
        } else {
          this.addVisable = false
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
      })
    },
    // 编辑角色信息
    editRoleListFro () {
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token')
        }),
        body: JSON.stringify({
          roleId: parseInt(this.editForm.roleId),
          roleName: this.editForm.roleName,
          level: parseInt(this.editForm.level)
        })
      }
      apiBus.editRoleList(para).then(res => {
        if (res.data.body.result === 1000) {
          this.$message.success('编辑角色成功！')
          this.editVisable = false
          this.filterForm.currentPage = 1
          this.getRoleListFro()
        } else if (res.data.body.result === 4001) {
          this.$message.error(res.data.body.resultDesp)
        } else {
          this.$message.error(res.data.body.resultDesp)
          this.editVisable = false
        }
      })
      .catch(error => {
        this.$message.error(error)
      })
    },
    // 编辑角色授权信息
    authorizeRoleListFro () {
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token')
        }),
        body: JSON.stringify({
          roleId: this.authorizeForm.roleId,
          permissions: this.authorizeForm.lastData
        })
      }
      console.log('authorizeRoleListFro入参')
      console.log(para)
      apiBus.authorizeRoleList(para).then(res => {
        console.log('authorizeRoleListFro回参')
        console.log(res)
        if (res.data.body.result === 1000) {
          this.$message.success('成功编辑角色权限！')
          this.authorizeVisable = false
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
      })
    },
    // 删除账户
    deleteRoleListFro () {
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token')
        }),
        body: JSON.stringify({
          roleId: parseInt(this.deleteForm.roleId)
        })
      }
      apiBus.deleteRoleList(para).then(res => {
        if (res.data.body.result === 1000) {
          this.$message.success('成功删除该角色！')
          this.filterForm.currentPage = 1
          this.getRoleListFro()
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
      })
    },
    // 从后台获得账户权限
    getSideItemsFro () {
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token')
        }),
        body: JSON.stringify({
          'roleId': parseInt(this.authorizeForm.roleId)
        })
      }
      console.log('getSideItemsFro入参')
      console.log(para)
      apiBus.getRoleItems(para).then(res => {
        if (res.data.body.result === 1000) {
          console.log('getSideItemsFro回参')
          console.log(res)
          this.authorizeVisable = true
          this.$nextTick(function () {
            this.authorizeForm.defaultExpandedKeys = this.getParentIdList(res.data.body.content.list)
            console.log('getParentIdList')
            console.log(this.authorizeForm.defaultExpandedKeys)
            // this.$refs.tree.defaultExpandedKeys = this.getParentIdList(res.data.body.content.list)
            this.$refs.tree.setCheckedKeys(this.getChildIdList(res.data.body.content.list))
          })
          // this.setDefaultTree()
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
      })
    }
  },
  mounted () {
    this.tableWidth = document.body.scrollWidth - 259 - 20
  }
}
</script>